// pages/address/list/index.js
import { reqAddressList, reqDelAddress } from '@/api/address'
import { swipeCellBehavior } from '@/behaviors/swipeCell'
const app = getApp()
Page({
  // 页面的初始数据
  behaviors: [swipeCellBehavior],
  data: {
    addressList: []
  },

  async getAddressList() {
    const res = await reqAddressList()
    // console.log(res)
    this.setData({
      addressList: res.data
    })
  },
  // 更新收货地址
  changeAddreaa(e) {
    console.log(e)
    if (this.flag !== '1') return
    // const id = e.currentTarget.dataset.id
    const id = e.currentTarget.dataset.id
    // js的 箭头函数加大括号需要return 或者将大括号和return都省略掉
    const orderlist = this.data.addressList.find((item) => {
      return item.id === id
    })
    // console.log(orderlist)
    if (orderlist) {
      app.globalData.address = orderlist
      wx.navigateBack()
    }
  },
  // 删除信息
  async delAddress(e) {
    const { id } = e.currentTarget.dataset
    const res = await wx.modal({
      content: '您确认要删除吗？'
    })
    if (res) {
      await reqDelAddress(id)
      wx.toast({ title: '收货地址删除成功' })
      this.getAddressList()
    } else {
    }
  },

  onShow() {
    this.getAddressList()
  },
  // onLoad() {

  // },
  // 去编辑页面
  toEdit(e) {
    const { id } = e.currentTarget.dataset
    // console.log(e)
    // console.log(id)
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  onLoad(option) {
    this.flag = option.flag
  }
})
